<?php

namespace App\Models;

use App\Http\Library\Map;
use App\Services\OrderService;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use JetBrains\PhpStorm\ArrayShape;

/**
 * App\Models\Service
 *
 * @property int $id
 * @property int|null $shop_id 门店ID
 * @property int|null $cid 分类ID
 * @property string|null $image 服务图片
 * @property string $title 服务标题
 * @property string|null $subtitle 服务描述
 * @property array|null $price 服务价格
 * @property string|null $worker_rates 服务价格
 * @property array $prices 车辆类型服务价格
 * @property array $member_prices 车辆类型服务会员价格
 * @property array $areas 地区价格与分成
 * @property array $content 图文介绍
 * @property int $sort 排序
 * @property int $status 状态:0=正常,1=隐藏
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property \App\Models\ServiceCategory|null $category
 * @property \App\Models\Shop|null $shop
 * @method static \Illuminate\Database\Eloquent\Builder|Service newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Service newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Service query()
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereCid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereImage($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service wherePrice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereSort($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereSubtitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereTitle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereUpdatedAt($value)
 * @mixin \Eloquent
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereAreas($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereCityRate0($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereCityRate1($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereDistrictRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service wherePrices($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereShopRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereWorkerRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Service whereContent($value)
 */
class Service extends Model
{
	use HasDateTimeFormatter;

    protected $casts = [
        'prices'=>'json','areas'=>'json','user_rate'=>'json',
        'city_rate0'=>'json','city_rate1'=>'json','district_rate'=>'json',
        'shop_rate'=>'json','worker_rate'=>'json','worker_rates'=>'json',
        'member_prices'=>'json',
    ];



    protected static function booted()
    {
        self::saving(function (Service $service){
            $prices = $service->prices;
            $typeList = CarBrand::getTypesList();
            foreach ($typeList as $key=>$type){
                if (!floatval($prices[$key])){
                    modelError("此{$type}价格不能设置小于等于0的数!");
                }
            }
            $service->price = min($prices);
            $areas = request()->input("areas");
            $areas = json_decode($areas,true);
            if ($areas){
                foreach ($areas as $area){
                    if (!$area['city']){
                        modelError("地区设置中的地区不能有空!");
                    }
                    $areaPrices = $area['prices'];
                    foreach ($typeList as $key=>$type){
                        if (!floatval($areaPrices[$key])){
                            modelError("地区设置中的{$type}价格不能设置小于等于0的数!");
                        }
                    }
                }
            }else{
                $areas = null;
            }
            $service->areas = $areas;
        });
        self::deleting(function (Service $service){
            $exit = Coupon::query()->where("cid",$service->id)->exists();
            if ($exit){
                modelError("此服务关联优惠券信息,不可删除!");
            }
        });
    }


    public static function getList(): array
    {
        $shop_id = request()->input("shop_id",0);
        $cid = request()->input("cid",0);
        $pageSize = request()->input("pageSize",0);
        $list = self::query()->where("shop_id",$shop_id)
            ->where("cid",$cid)
            ->orderByDesc("sort")
            ->orderByDesc("id")
            ->paginate($pageSize);
        foreach ($list as $item){
            $item->image = cdn_url($item->image);
            $item->member_prices = $item->member_prices?:$item->prices;
        }
        return [
          'items'=> $list->items(),
          'total'=>  $list->total(),
          'lastPage'=> $list->lastPage()
        ];
    }

    public static function getPrice($user_id): array
    {
        $service_id = request()->post("service_id");
        $car_id = request()->post("car_id");
        $price = 0;
        $service = self::whereId($service_id)->first();
        if ($service){
            $price = $service->price;
            $prices = $service->prices;
            $member_prices = $service->member_prices;
            $member_price = $service->price;
            $worker_rate = 0;
            $worker_rates = $service->worker_rates;
            if ($car_id){
                $car = UserCar::find($car_id);
            }else{
                $car = UserCar::whereUserId($user_id)->where("is_default",1)->first();
            }
            $types = CarBrand::getTypesList();
            $shop = ShopUser::query()->with(['agent'])->where("id",$service->shop_id)->first();
            $agent = $shop->agent;
            if ($agent){
                $agent_rate = $agent->agent_rate;
                $top_rate = $agent->top_rate;
                $top_top_rate = $agent->top_top_rate;
                $agent_id = $shop->agent_id;
            }else{
                $top_rate = 0;
                $agent_rate = 0;
                $top_top_rate = 0;
                $agent_id = 0;
            }
            if ($car&&$prices){
                $type = $car->type;
                $key = array_search($type,$types);
                if ($key!==false){
                    $price = $prices[$key];
                    $worker_rate = $worker_rates[$key]??0;
                    if (isset($member_prices[$key])){
                        $member_price = $member_prices[$key];
                    }
                }
            }
            return [
                'price'=>$price,
                'top_rate'=>$top_rate,
                'top_top_rate'=>$top_top_rate,
                'worker_rate'=>$worker_rate,
                'agent_rate'=>$agent_rate,
                'agent_id'=>$agent_id,
                'car'=>$car,
                'member_price'=>$member_price,
            ];
        }else{
            return [
                'price'=>$price,
                'top_rate'=>0,
                'top_top_rate'=>0,
                'worker_rate'=>0,
                'agent_rate'=>0,
                'agent_id'=>0,
                'car'=>[],
                'member_price'=>0,
            ];
        }
    }

    public function category(): HasOne
    {
        return $this->hasOne(ServiceCategory::class,"id","cid");
    }

    public function shop(): HasOne
    {
        return $this->hasOne(ShopUser::class,"id","shop_id");
    }
}
